package com.imooc.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * Created by zhanglei on 2019/3/23.
 * 用于测试熔断器
 * 1.引入依赖
 * 2.在启动类上加注解 @EnableCircuitBreaker
 * 3.方法上加注解 @HystrixCommand
 * 4.指定服务降级后执行的方法
 *
 * feign中使用熔断器:
 * 1.提供服务的feign接口中指定fallback来指定如果产生服务降级时访问的类,该类实现接口,接口出错则访问该类中对应的方法
 * 2.调用服务方配置feign.hystrix.enabled: true
 * 3.注意扫描包的问题
 */
@RestController
//发生错误后执行的方法
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    //这些都可以放到配置文件中
    //超时配置
//	@HystrixCommand(commandProperties = {
//			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//	})

    /**
     * 断路器模式
     * 如果错误率超过设置的值,就会触发服务降级,本来能够成功的也会降级
     * @param number
     * @return
     */
    @HystrixCommand(commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  				    //设置熔断
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),	        //请求数达到后才计算
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),   //熔断时间
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),	    //错误率
	})


//    @HystrixCommand
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {

        if(number % 2 == 0) {
            return "success";
        }

        //调用product服务
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://localhost:8080/product/listForOrder", Arrays.asList("157875196366160022"),String.class);
    }

    private String defaultFallback() {
        return "默认提示:太拥挤了,请稍后~~";
    }


}
